import OrderCard from "@/components/OrderCard"
import Page from "@/components/page"
import { GoodsFields } from "@/interfaces/GoodsEntity"
import { OrderEntity, OrderFields } from "@/interfaces/OrderEntity"
import { ShopFields } from "@/interfaces/ShopEntity"
import { UserFields } from "@/interfaces/UserEntity"
import { OrderOnGoodsFields } from "@/interfaces/order-goods.entity"
import { gql, useMutation, useQuery } from "@apollo/client"

import { useCallback, useMemo } from "react"

const SelAllOrderQuery = gql`
  query SelALlOrder{
    selALlOrder{
      ${OrderFields}
      OrderOnGoods{
        ${OrderOnGoodsFields}
        goods{
          ${GoodsFields}
        }
      }
      shop{
        ${ShopFields}
      }
      user{
        ${UserFields}
      }
    }
  }
`
const DeliveryOrderMutation = gql`
    mutation DeliveryOrder($id:Int!){
        deliveryOrder(id:$id){
            id
        }
    }
`
const OrderPage = () => {
  const { data, refetch } = useQuery(SelAllOrderQuery)
  const orders: OrderEntity[] = useMemo(() => data?.selALlOrder || [], [data]);
  const [deliveryOrder] = useMutation(DeliveryOrderMutation, {
    onCompleted() {
      refetch()
    }
  })
  const onFinish = useCallback((order: OrderEntity) => {
    deliveryOrder({ variables: { id: order.id } })
  }, [])
  return (
    <Page>
      <div className="flex flex-wrap gap-4" style={{ maxWidth: "800px" }}>
        {orders.map((order) => (
          <OrderCard
            key={order.id}
            order={order}
            onFinish={onFinish}
          />
        ))}
      </div>
    </Page>
  )
}
export default OrderPage